package com.bysc.userservice.handler;
 
import com.alibaba.fastjson.JSON;
import com.bysc.baseservice.config.RabbitmqConfig;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.message.NotificationMessage;
import com.bysc.userservice.controller.WebsocketNoticeController;
import com.bysc.userservice.entity.NoticeContent;
import com.bysc.userservice.service.NoticeContentService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class ReceiveHandler {
    @Autowired
    WebsocketNoticeController websocketNoticeController;
    @Autowired
    NoticeContentService noticeContentService;
    //监听notice队列
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_NOTICE})
    public void receive_notice(Message message, Channel channel){

        try {
            NotificationMessage notificationMessage = JSON.parseObject(message.getBody(), NotificationMessage.class);
            String noticedUserId = notificationMessage.getNoticedUserId();
            if ("0".equals(noticedUserId)) { //发送给全体用户
                websocketNoticeController.sendToAll(notificationMessage);
            }
            else if ("1".equals(noticedUserId)) { //发送给协会成员
                websocketNoticeController.sendToClub(notificationMessage);
            }else { // 发送给特定用户
                websocketNoticeController.sendToOne(notificationMessage);
            }
            // 手动发送 ACK
            doAck(message,channel,notificationMessage);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException ex) {
                throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_NOTICE_FAIL);
            }
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_NOTICE_FAIL);
        }
    }

    private void doAck(Message message, Channel channel, NotificationMessage notificationMessage) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        NoticeContent noticeContent = new NoticeContent();
        BeanUtils.copyProperties(notificationMessage,noticeContent);
        noticeContentService.save(noticeContent);
    }
}